Server
public class Server implements Runnable {
static Thread t1, t2;
static ServerSocket ss;
static Socket s;
static BufferedReader br1, br2;
static PrintWriter pr;
public void run() {
try {
if (Thread.currentThread() == t1) {
while (true) {
String str1 = br1.readLine();
if (str1.equals("bye")) {
System.out.println("Server says : "+str1);
pr.println(str1);
pr.flush();
break;
} else {
System.out.println("Server says : "+str1);
pr.println(str1);
pr.flush();
}
}
}
if (Thread.currentThread() == t2) {
while (true) {
String str2 = br2.readLine();
if (str2.equals("bye")) {
System.out.println("Client says : "+str2);
t1.stop();
break;
} else {
System.out.println("Client says : "+str2);
}
}
ss.close();
}
} catch (IOException ex) {
Logger.getLogger(TestSer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) throws IOException {
ss = new ServerSocket(1234);
s = ss.accept();
br1 = new BufferedReader(new InputStreamReader(System.in));
br2 = new BufferedReader(new InputStreamReader(s.getInputStream()));
pr = new PrintWriter(s.getOutputStream());
t1 = new Thread(new TestSer());
t1.start();
t2 = new Thread(new TestSer());
t2.start();
}
}
Output:
hai
Server says : hai
Client says : hello
bye
Server says : bye
Client says : bye